using System.Buffers;
using System.Buffers.Binary;
using System.Text;
using SuperSocket.ProtoBase;

namespace KestrelClientWithSuperSocket;

internal sealed class EachPackageEncode : IPackageEncoder<EachPackage>
{
    private const int HeadSize = sizeof(ushort);

    public int Encode(IBufferWriter<byte> writer, EachPackage pack)
    {
        var headBuffer = writer.GetSpan(HeadSize);
        writer.Advance(HeadSize);   
        
        var bodyLength = writer.Write(pack.Content, Encoding.UTF8);

        BinaryPrimitives.WriteInt16BigEndian(headBuffer, (short)bodyLength);

        return bodyLength + HeadSize;
    }
}